<template>
  <el-dialog
    :title="title"
    v-model="dialogVisible"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    width="700"
    @close="handleClose"
  >
    <div class="upload-file">
      <div v-if="formValue?.tip" class="text-[red] my-[2px]">说明:{{ formValue.tip }}</div>
      <div
        style="border: 1px dashed #3366f1"
        :class="['upload-box', fileList.length ? 'uploadActive' : '']"
      >
        <el-upload
          multiple
          action="#"
          :file-list="fileList"
          :limit="limit"
          :on-exceed="handleExceed"
          :before-upload="beforeUpload"
          :on-success="handleSuccess"
          :http-request="handleHttpRequest"
          :show-file-list="false"
          :accept="fileType"
          class="upload-file-uploader"
          ref="fileUpload"
        >
          <el-button type="primary" text>文件上传</el-button>
        </el-upload>
        <div class="text-gray-500 text-center">
          按住Ctrl可批量选择多个文件上传
        </div>
      </div>
      <!-- 文件列表 -->
      <transition-group
        class="file-box"
        name="el-fade-in-linear"
        tag="ul"
        v-if="fileList.length"
      >
        <div class="text-gray-400 w-full">已上传</div>
        <div
          class="mb-4 mr-10 flex items-center text-center"
          v-for="(file, index) in fileList"
          :key="index"
        >
          <span class="mr-2 link-style">
            <span> {{ file.name }} </span>
          </span>
          <div class="ele-upload-list__item-content-action">
            <svg-icon
              class="text-red-500"
              icon-class="del"
              @click="handleDelete(index)"
            ></svg-icon>
          </div>
        </div>
      </transition-group>
    </div>
    <template #footer>
      <el-button class="ml-5" @click="handleClose(false)" :loading="loading"
        >取消</el-button
      >
      <el-button type="primary" @click="handleSave" :loading="loading"
        >提交</el-button
      >
    </template>
  </el-dialog>
</template>

<script setup>
import { genFileId, ElMessage } from "element-plus";
import { uploadFile } from "@/api/public.js";
import { submit } from "./config.js";
import { tipMessage } from "@/hooks/tool.js";
const props = defineProps({
  // 数量限制
  limit: {
    type: Number,
    default: 1,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 100,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: String,
    default: "jpg,jpeg,png,pdf",
  },
  title: { type: String, default: "上传税金单" },
});
const { fileType, title } = toRefs(props);
const emit = defineEmits(["refresh", "close"]);
const dialogVisible = ref(false);
const fileList = ref([]);
const fileUpload = ref();
const formValue = reactive({});
const open = (data) => {
  formValue.urlType = data?.urlType || null;
  formValue.params = data?.params || {};
  formValue.batch_tip = data?.batch_tip || false;
  formValue.tip = data?.tip || "";
  dialogVisible.value = true;
};
const beforeUpload = (file) => {
  const limitSize = 500;
  const isLt500M = file.size / 1024 / 1024 < limitSize;
  if (!isLt500M) {
    ElMessage.error(`上传文件大小不能超过 ${limitSize}MB!`);
  }
  return isLt500M;
};

const handleExceed = (files) => {
  fileUpload.value.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  fileUpload.value.handleStart(file);
  fileUpload.value.submit();
};

const handleSuccess = (_res, _file, _fileList) => {
  processFileList(_fileList);
};

const processFileList = (_fileList) => {
  const _data = _fileList.map((item) => {
    if (!item.filepath && item.response) {
      const response = item.response;
      return { ...item, ...response };
    }
    return item;
  });
  fileList.value = _data;
};

const handleDelete = (e) => {
  const _data = fileList.value;
  const _index = _data.find((n) => n.uid === e.uid);
  fileList.value.splice(_index, 1);
};

const handleHttpRequest = async (options) => {
  let formData = new FormData();
  const { file } = options;
  formData.append("file", file);
  try {
    const { data } = await uploadFile(formData, "f");
    return data;
  } catch (e) {
    console.error(e);
    options.onError(e);
  }
};
const loading = ref(false);
const handleSave = async () => {
  let file = fileList.value;
  if (file?.length === 0) {
    ElMessage.warning("请上传文件");
    return;
  }
  if (!formValue?.urlType) {
    return;
  }
  loading.value = true;
  let files;
  if (file.length == 1) {
    files = [file[0].response];
  } else {
    files = file.map((item) => item.response);
  }

  try {
    const { code, message, data } = await submit(formValue.urlType, {
      files: files,
      ...formValue.params,
    });
    if (code !== 200) {
      ElMessage.warning(message);
      return;
    }
    if (formValue?.batch_tip) {
      tipMessage(data);
    } else {
      ElMessage.success("导入成功!");
    }

    handleClose(true);
  } catch (error) {
  } finally {
    loading.value = false;
  }
};
const handleClose = (refresh) => {
  fileList.value = [];
  clearFiles();
  dialogVisible.value = false;
  emit("close");
  if (refresh) emit("refresh");
};

const clearFiles = () => {
  fileUpload.value.clearFiles();
};
defineExpose({ clearFiles, open });
</script>

<style scoped lang="scss">
.upload-file-uploader {
  margin-bottom: 5px;
  text-align: center;
}

.upload-file-list .el-upload-list__item {
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}

.link-style {
  min-width: 240px;
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.upload-box {
  display: flex;
  flex-direction: column;
  justify-items: center;
  align-items: center;
  padding: 80px 0;
}

.uploadActive {
  height: auto;
  padding: 16px;
}

.file-box {
  background: #fafafa;
  border-radius: 4px;
  margin-top: 16px;
  padding: 40px 0;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  text-align: center;
}
</style>
